package idv.loveloser.servlet;

import idv.loveloser.dao.MdlCourse;
import idv.loveloser.dao.MdlCourseDAO;
import idv.loveloser.dao.MdlUserDAO;
import idv.loveloser.dao.MdlWebservicesSessions;
import idv.loveloser.dao.MdlWebservicesSessionsDAO;
import idv.loveloser.util.Util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonArray;

public class GetCourses extends HttpServlet {
	private MdlCourseDAO courseDAO=new MdlCourseDAO();
	private MdlWebservicesSessionsDAO sessionDAO = new MdlWebservicesSessionsDAO();
	
	/**
	 * Constructor of the object.
	 */
	public GetCourses() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		List<MdlCourse> coursesList= new ArrayList<MdlCourse>();
		String client = request.getParameter("client");
		String sessionKey = request.getParameter("sessionKey");
		if(Util.isAuthorised(client, sessionKey)){
			System.out.println("[Util.isAuthorised:]:true");
			coursesList=courseDAO.findAll();
			System.out.println("[Courses Size:]:"+coursesList.size());
		}
		String jsonStr="";
		Gson gson = new Gson();
		jsonStr=gson.toJson(coursesList);
		out.println(jsonStr);
		
		out.flush();
		out.close();
	}
	 
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
